<!-- ERC --巡检组 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common">
      <div class="equip-group-list">
        <px-input v-model="listSearch" class="w-[380px] mb-[8px] self-center" placeholder="请输入" :prefix-icon="Search" @change="listSearchFun" />
        <px-scrollbar :key="forceUpdate">
          <div
            v-for="item in searchList"
            :key="item.id"
            class="equip-group-list-item"
            :class="{ 'item-active': equipSelected?.id === item.id }"
            @click="equipGroupSelect(item)"
          >
            <div class="equip-group-list-item-title">
              <ReTextTooltip :content="item.name" :style="{ width: '100%' }" />
            </div>
            <px-dropdown v-if="isBtnListShow">
              <px-icon :size="16">
                <MoreFilled />
              </px-icon>
              <template #dropdown>
                <px-dropdown-menu>
                  <px-dropdown-item>
                    <px-button v-has="'ERC_INSPECT_GROUP_EDIT_GROUP'" link type="primary" :icon="EditPen" @click="groupEdit(item)">编辑</px-button>
                  </px-dropdown-item>
                  <px-dropdown-item>
                    <px-button v-has="'ERC_INSPECT_GROUP_DEL_GROUP'" link type="danger" :icon="Delete" @click="groupDelete(item)"
                      >删除</px-button
                    ></px-dropdown-item
                  >
                </px-dropdown-menu>
              </template>
            </px-dropdown>
          </div>
        </px-scrollbar>
        <px-button v-has="'ERC_INSPECT_GROUP_ADD_GROUP'" type="primary" plain class="w-[380px] self-center" @click="isView = true"
          >新增巡检组</px-button
        >
      </div>
      <div class="equip-group-table">
        <px-button v-has="'ERC_INSPECT_GROUP_ADD_OPT'" type="primary" size="small" border class="w-[116px] h-[32px] mb-[10px]" @click="addTableItem"
          >新增巡检人员</px-button
        >
        <div class="overflow-auto">
          <px-table
            :data="tableData"
            class="custom-form-ui equip-table"
            table-layout="auto"
            border
            header-cell-class-name="equip-group-table-header"
            height="calc(100vh - 200px)"
          >
            <px-table-column width="70px" type="index" align="center" label="序号" />
            <px-table-column min-width="200px" prop="operateId" label="巡检人员">
              <template #default="scope">
                <px-select-v2
                  v-if="scope.row.isEditor"
                  v-model="scope.row.operateId"
                  filterable
                  clearable
                  :options="peopleList"
                  placeholder="请选择巡检人员"
                  @change="maintChange(scope.row)"
                />
                <span v-else>{{ getUserLabel(scope.row.operateId) }}</span>
              </template>
            </px-table-column>
            <px-table-column width="70px" align="center" label="操作">
              <template #default="scope">
                <div v-if="scope.row.isEditor" class="flex justify-between text-[#3B82F6]">
                  <px-icon @click="itemCheck(scope.row)"><Check /></px-icon>
                  <px-icon @click="itemClose(scope.row)"><Close /></px-icon>
                </div>
                <div v-else class="flex justify-between">
                  <px-button v-has="'ERC_INSPECT_GROUP_EDIT_OPT'" type="primary" link :icon="EditPen" @click="itemEdit(scope.row)" />
                  <px-button v-has="'ERC_INSPECT_GROUP_DEL_OPT'" type="danger" link :icon="Delete" @click="itemDelete(scope.row)" />
                </div>
              </template>
            </px-table-column>
          </px-table>
        </div>
      </div>
    </div>
    <GroupEmpty v-model:isMain="isMain" v-model:isView="isView" v-model:isEmpty="isEmpty" />
    <px-dialog v-model="isView" destroy-on-close :title="isEditor ? '编辑巡检组' : '新增巡检组'" :close-on-click-modal="false" width="640px">
      <px-form ref="formEl" :model="dialogFrom" label-width="120px" :rules="rules" label-position="right">
        <px-form-item label="巡检组名称" prop="name">
          <px-input v-model="dialogFrom.name" maxlength="50" class="w-[100%]" />
        </px-form-item>
      </px-form>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="cancel">取消</px-button>
          <px-button type="primary" @click="submit"> 确定 </px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  delOpsGroup,
  delOpsGroupOperate,
  queryGroupList,
  queryOperateList,
  saveOpsGroup,
  saveOpsGroupOperate,
  updateOpsGroup,
  updateOpsGroupOperate
} from "@/api/erc/group";
import ReTextTooltip from "@/components/ReTextTooltip";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { Check, Close, Delete, EditPen, MoreFilled, Search } from "@px-ui/icons-vue";
import { computed, onMounted, reactive, ref, toRefs } from "vue";

import { PxMessage, PxMessageBox } from "px-ui";
import GroupEmpty from "./components/GroupEmpty.vue";

defineOptions({
  name: "ERC_INSPECT_GROUP"
});
const formEl = ref();
const state = reactive<any>({
  isMain: true, //列表页显示
  isView: false, //新增弹窗显示
  isEmpty: true, //空页面显示
  isEditor: false, //编辑弹框
  isBtnListShow: true, //下拉按钮列表
  listSearch: "",
  searchList: [],
  forceUpdate: 0,
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  equipGroup: [],
  equipSelected: {},
  dialogFrom: {
    name: ""
  },
  rules: {
    name: { required: true, message: "请输入巡检组名称", trigger: ["blur", "change"] }
  },
  tableData: [],
  peopleList: [] //下拉选人
});
const {
  isMain,
  isView,
  isEmpty,
  isEditor,
  equipSelected,
  listSearch,

  peopleList,
  tableData,
  dialogFrom,
  rules,
  equipGroup,
  forceUpdate,
  isBtnListShow
} = toRefs(state);
const searchList = computed(() => {
  if (!listSearch.value && listSearch.value !== 0) {
    //这里数据刷新但是页面不刷新使用forceUpdate使组件强刷
    return equipGroup.value;
  }
  return equipGroup.value?.filter(item => item?.name?.indexOf(listSearch.value) !== -1);
});

onMounted(async () => {
  permission();
  await getEuipGroup();

  peopleList.value = await getEmployeeIdAndName(["ERC&FP"]); //下拉选人
});
async function getEuipGroup() {
  try {
    equipGroup.value = await queryGroupList({
      name: ""
    });
    if (equipGroup.value?.length > 0) {
      isEmpty.value = false;
    } else {
      isEmpty.value = true;
      isMain.value = false;
    }
  } catch (e) {
    console.log(e);
  }
}
async function getOperateTable(id) {
  try {
    tableData.value = await queryOperateList({ id });
  } catch (e) {
    console.error(e);
  }
}
async function itemCheck(item) {
  const { operateId } = item || {};
  if (!operateId) {
    PxMessage.warning("请选择巡检人员");
    return false;
  } else {
    try {
      const { id: groupId } = equipSelected.value;
      const { operateId, operateName, agentName, id } = item;
      if (!id) {
        let saveData = { groupId, operateId, operateName, agentName };
        try {
          await saveOpsGroupOperate(saveData);
          PxMessage.success("保存成功");
        } catch (e) {
          return;
        }
      } else {
        let saveData = { groupId, operateId, operateName, agentName, id };
        try {
          await updateOpsGroupOperate(saveData);
          PxMessage.success("编辑成功");
        } catch (e) {
          return;
        }
      }
      await getOperateTable(groupId);
    } catch (e) {
      console.error(e);
    }
  }
  item.isEditor = false;
}
function itemClose(item) {
  const { operateId, id } = item || {};
  if (!operateId || !id) {
    tableData.value?.shift();
    return false;
  }
  item.isEditor = false;
}
function groupEdit(item) {
  Object.assign(dialogFrom.value, item);
  isView.value = true;
  isEditor.value = true;
  console.log(item);
}
function groupDelete(item) {
  const { id, name } = item;

  PxMessageBox.confirm(`是否删除${name}？`, "温馨提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delOpsGroup({ id });
      PxMessage.success("删除成功");
      equipGroup.value = await queryGroupList({
        name: ""
      });
      tableData.value = null;
    })
    .catch(() => {});
}

function itemEdit(item) {
  item.isEditor = true;
}
function itemDelete(item) {
  const { id } = item;

  PxMessageBox.confirm(`是否删除该数据？`, "温馨提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const { id: groupId } = equipSelected.value;
      await delOpsGroupOperate({ id });
      await getOperateTable(groupId);
      PxMessage.success("删除成功");
    })
    .catch(e => {
      console.error(e);
    });
}
function listSearchFun() {
  console.log("search", listSearch.value);
}
function maintChange(item) {
  const { operateId } = item;

  if (operateId) {
    const arr = peopleList.value.filter(item => {
      return item.value === operateId;
    });
    if (arr && arr.length > 0) {
      item.operateName = arr[0].label;
    }
  }
}

function cancel() {
  formEl.value?.resetFields();
  //不知道为啥resetFields无效需要手动再清理一下
  dialogFrom.value = {
    name: ""
  };
  isView.value = false;
  isEditor.value = false;
}
async function submit() {
  if (!formEl.value) return;
  await formEl.value.validate(async valid => {
    if (valid) {
      console.log("submit", dialogFrom);
      try {
        if (!isEditor.value) {
          await saveOpsGroup(dialogFrom.value);
        } else {
          await updateOpsGroup(dialogFrom.value);
        }

        equipGroup.value = await queryGroupList({
          name: ""
        });
        //强刷左侧列表，推测是key为id但是编辑后id不变导致页面不刷新
        forceUpdate.value++;
        if (equipGroup.value && equipGroup.value.length > 0) {
          //编辑时不切换焦点
          if (!isEditor.value) {
            equipGroupSelect(equipGroup.value[equipGroup.value.length - 1]);
          }
        }
        if (equipGroup.value?.length > 0) {
          isEmpty.value = false;
          isMain.value = true;
          cancel();
        }
        console.log(equipGroup.value);
      } catch (e) {
        console.error(e);
      }
    }
  });
}

function addTableItem() {
  if (tableData.value.find(item => item.isEditor)) {
    PxMessage.warning("请保存当前巡检人员。");
    return;
  }
  if (!equipSelected.value || JSON.stringify(equipSelected.value) === "{}") return;
  tableData.value.unshift({
    operateId: null,
    operateName: "",
    agentName: "",
    isEditor: true
  });
}
function equipGroupSelect(item) {
  equipSelected.value = item;
  if (item?.id) {
    getOperateTable(item?.id);
  }
}

function permission() {
  const permissionList = localStorage.getItem("permissionList");
  const pl = permissionList.split(",");

  if (
    permissionList === "**" ||
    (pl?.length && pl?.includes("ERC_INSPECT_GROUP_EDIT_GROUP")) ||
    (pl?.length && pl?.includes("ERC_INSPECT_GROUP_DEL_GROUP"))
  ) {
    isBtnListShow.value = true;
  } else {
    isBtnListShow.value = false;
  }
}
const getUserLabel = id => {
  const arr = peopleList.value.filter(item => {
    return item.userId === id;
  });
  if (arr && arr.length > 0) {
    return arr[0].label;
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.equip-wrap-common {
  display: flex;
  min-width: 1100px;

  .equip-group-list {
    display: flex;
    flex-direction: column;
    flex-grow: 0;
    flex-shrink: 0;
    align-items: flex-end;
    width: 400px;
    height: 100%;
    padding-top: 16px;
    padding-bottom: 16px;
    border-right: 1px solid #dcdcdc;

    &-item {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      width: 380px;
      height: 62px;
      padding-right: 14px;
      cursor: pointer;
      box-shadow: inset 0 -1px 0 0 rgb(0 0 0 / 10%);

      &-title {
        display: flex;
        flex-direction: column;
        flex-grow: 1;
        align-items: flex-start;
        justify-content: center;
        width: 90%;
        height: 100%;
        padding-left: 16px;
        margin-bottom: 3px;
        font-size: 14px;

        .title-tag {
          display: flex;
          align-items: center;
          justify-content: center;
          width: auto;
          height: 22px;
          padding: 8px;
          font-size: 12px;
          font-weight: 400;
          line-height: 20px;
          color: #909399;
          background: #f4f4f5;
          border: 1px solid #e9e9eb;
          border-radius: 4px;
        }
      }

      i,
      svg {
        outline: none;
      }
    }

    .item-active {
      background: #ecf5ff;
      border-right: 2px solid #3b82f6;
      box-shadow: inset 0 -1px 0 0 rgb(0 0 0 / 10%);

      & > :first-child {
        color: #3b82f6;
      }
    }
  }

  .equip-group-table {
    display: flex;
    flex-direction: column;
    flex-grow: 1;
    min-width: 700px;
    height: 100%;
    padding: 16px 24px;
    :deep(.equip-table) {
      .cell {
        color: #000;
        font-size: bold;
      }
      .px-select-v2 {
        width: 100%;
        border: 1px solid #dfdfdf;
      }
    }
  }

  :deep(.equip-group-table-header) {
    background: #e7eefb;
  }
  :deep(.px-table__cell) {
    .cell {
      height: auto !important;
    }
  }
}
</style>
